/** 
  期末总评成绩
*/
<template>
  <div class="final-assess-result-container">
    <!-- 课程列表开始 -->
    <div v-if="indexKey === 1">
      <el-card shadow="never" body-style="padding: 24px;" class="condition-card">
        <el-form label-position="right" label-suffix="：" label-width="100px">
          <el-row :gutter="24" style="height: 50px;">
            <el-col :span="3" style="line-height: 33px;">
              <span class="condition-title">{{ $t("message.filterCondition") }}</span>
            </el-col>
            <!-- 学期 -->
            <el-col :span="8">
              <el-form-item :label="$t('scoreEntrySwitch.semester')">
                <calendar-select ref="calendarSelect" v-model="queryForm.condition.calendarId" @change="changeCalendarId" :placeholder="$t('common.pla.pleaseSelect')"></calendar-select>
              </el-form-item>
            </el-col>
            <!-- 考试类型 -->
            <el-col :span="8">
              <el-form-item :label="$t('scoreEntryMana.examType')">
                <el-select v-model="queryForm.condition.examType" @change="changeExamType" style="width: 100%">
                  <el-option
                    v-for="item in options.examType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <div style="float: right;margin-right: 10px;">
              <el-button @click="reset()">{{ $t('message.reset') }}</el-button>
              <el-button type="primary" @click="onSubmit()">{{ $t('message.filter') }}</el-button>
            </div>
          </el-row>
        </el-form>
      </el-card>
      <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
        <h1 class="condition-title">{{ $t('scoreEntryMana.courseList') }}</h1>
        <h5 v-if="enterabledTime.hasRight" style="color: #d9001b;">{{ $t('scoreEntryMana.enterabledTime') }}：{{ enterabledTime.startTime }}--{{ enterabledTime.endTime }}</h5>
        <h5 v-else style="color: #d9001b;">{{ $t('scoreEntryMana.enterabledTime') }}：--</h5>
        <!-- {{ $t('scoreEntryMana.notSetEntrySwitch') }} -->
        <edu-table :pagination="false" :order='true' :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
          <!-- 课程序号 -->
          <edu-table-column :label="$t('scoreEntryMana.courseNum')" prop="courseNo"></edu-table-column>
          <!-- 课程名称 -->
          <edu-table-column :label="$t('scoreEntryMana.courseName')" prop="courseName"></edu-table-column>
          <!-- 课程类别 -->
          <edu-table-column :label="$t('scoreEntryMana.courseType')" prop="courseLableName"></edu-table-column>
          <!-- 学分 -->
          <edu-table-column :label="$t('scoreEntryMana.credit')" prop="credits"></edu-table-column>
          <!-- 周数 -->
          <edu-table-column :label="$t('scoreEntryMana.weekNumber')" prop="weeks"></edu-table-column>
          <!-- 周课时 -->
          <edu-table-column :label="$t('scoreEntryMana.weekClassHours')" prop="weeksHour"></edu-table-column>
          <!-- 人数 -->
          <edu-table-column :label="$t('scoreEntryMana.numOfPeople')" prop="eleNumber"></edu-table-column>
          <!-- 期末总评成绩/重缓考成绩 -->
          <edu-table-column :label="queryForm.condition.examType === '2' ? $t('scoreEntryMana.finalAssessScore') : $t('redelayTestScoreMana.redelayScore')" prop="releaseType" fit width="350">
            <template slot-scope="scope">
              <!-- 空白登分表 -->
              <el-button v-if="permitToScoreBlankSheet" type="text" @click="scoreBlankSheet(scope.row)">{{ $t('scoreEntryMana.blankScoreSheet') }}</el-button>
              <!-- 查看 -->
              <el-button v-if="permitToDetail" type="text" @click="selectCourseInfo(scope.row)">{{ $t('scoreMangementBase.select') }}</el-button>
              <!-- 存档成绩单 -->
              <el-button type="text" @click="checkToBlanket(scope.row)">{{ $t('scoreMangementBase.archiveTranscripts') }}</el-button>
              <!-- 成绩录入(未发布) -->
              <el-button v-if="permitToScoreEntry && scope.row.releaseType === '0' && scope.row.canInput" type="text" @click="scoreEntry(scope.row)">{{ $t('scoreEntryMana.scoreEntry') }}</el-button>
              <!-- 清空成绩 -->
              <el-button v-if="permitToScoreEntry && scope.row.releaseType === '0' && scope.row.canInput" type="text" @click="deleterScore(scope.row)">{{ $t('scoreMangementBase.deleterScore') }}</el-button>
              <!-- 已发布 -->
              <span style="margin-left: 10px;font-size: 12px;" v-if="scope.row.releaseType === '1'" type="text">{{ $t('scoreEntryMana.alreadyPublish') }}</span>
            </template>
          </edu-table-column>
        </edu-table>
        <el-row type="flex" class="row-bg" justify="end">
          <el-col>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryForm.pageNum_"
              :page-sizes="[20, 40, 80, 100]"
              :page-size="queryForm.pageSize_"
              layout="total, sizes, prev, pager, next, jumper"
              :total="queryForm.total_"
              style="float:right;margin-top:10px"
            ></el-pagination>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <!-- 课程列表结束 -->
    <!-- 空白登分表开始 -->
    <div v-if="indexKey === 2">
      <blank-sheet-score :detailInfo="detailInfo" @refresh-main-page="refreshMainPage()"></blank-sheet-score>
    </div>
    <!-- 空白登分表结束 -->
    <!-- 查看开始 -->
    <div v-if="indexKey === 3">
      <select-score :detailInfo="detailInfo" @refresh-main-page="refreshMainPage()"></select-score>
    </div>
    <!-- 查看结束 -->
    <!-- 成绩录入开始 -->
    <div v-if="indexKey === 4">
      <score-entry :detailInfo="detailInfo" :admitToEntryType="admitToEntryType" @refresh-main-page="refreshMainPage()"></score-entry>
    </div>
    <!-- 成绩录入结束 -->
    <el-dialog
      :before-close="beforeClose"
      :title="title"
      width="70%"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="dialogForm" label-position="right" ref="dialogForm" label-width="120px">
        <el-row>
          <el-col :span="16">
            <!-- 短信验证码 -->
            <el-form-item
              :label="$t('scoreEntryMana.verificationCode') + '：'"
              prop="verificationCode"
              :rules="[{ required: true, message: $t('scoreEntryMana.requireVerificationCode'), trigger: 'blur' },{ validator: validateMessage, trigger: 'blur'}]">
              <el-input :placeholder="$t('common.pla.pleaseInput')" v-model="dialogForm.verificationCode" :maxlength="6" clearable style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 密码序号 -->
            <el-form-item :label="$t('scoreEntryMana.passwordNum') + '：'">{{ passwordNum }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel('dialogForm')">{{ $t('common.btn.cancel') }}</el-button>
        <el-button type="primary" @click="confirm('dialogForm')">{{ $t('common.btn.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import scoreManagementApi from 'common/src/api/scoreManagement/scoreManagement';
import blankSheetScore from './blankSheetScore';
import selectScore from './selectScore';
import scoreEntry from './scoreEntry';
import * as INDEX from 'common/src/utils/index';
import api from 'common/src/api/score/bachelor/gradeEntry';
export default {
  components: {
    'blank-sheet-score': blankSheetScore,
    'select-score': selectScore,
    'score-entry': scoreEntry
  },
  data () {
    return {
      indexKey: 1,
      auths: [],
      userInfo: {},
      needMessageVerification: false,
      passwordNum: '05',
      permitToScoreBlankSheet: false,
      permitToDetail: false,
      permitToScoreEntry: false,
      multipleSelection: [],
      messageInfo: {},
      dataList: [],
      queryForm: {
        condition: {
          calendarId: '',
          examType: '2', // 期末2 重缓考1
          uid: ''
        },
        pageNum_: 1,
        pageSize_: 20,
        total_: 0
      },
      enterabledTime: {
        hasRight: false,
        startTime: '',
        endTime: ''
      },
      options: {
        examType: [
          {
            key: '2',
            label: '期末总评',
            value: '2'
          },
          {
            key: '1',
            label: '重缓考',
            value: '1'
          }
        ]
      },
      title: '',
      dialogVisible: false,
      dialogForm: {
        verificationCode: ''
      },
      detailInfo: {},
      admitToEntryType: ''
    }
  },
  async created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths
      }
      if (JSON.parse(localStorage.getItem("sessiondata")).mockUser) {
        this.userInfo = JSON.parse(localStorage.getItem("sessiondata")).mockUser
      } else {
        this.userInfo = JSON.parse(localStorage.getItem("sessiondata")).user
      }
    }
    this.queryForm.condition.uid = this.userInfo.uid
    // 若全局设置勾选短信验证，点击成绩录入即当前登录账号绑定手机发送短信验证码，输入短信验证通过后才能录入成绩。
    // 若全局设置未勾选则直接跳转至“成绩构成、成绩录入”
    let globalInfoRes = await scoreManagementApi.queryGlobalSetInfo({
      "setType": ""
    })
    if (globalInfoRes.code === 200 && globalInfoRes.data.length > 0) {
      this.needMessageVerification = globalInfoRes.data[0].isCheckMsg === 'Y' || !globalInfoRes.data[0].isCheckMsg
    }
  },
  mounted() {
   
  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback()
      }
    },
    // 校验短信验证码
    validateMessage(rule, value, callback) {
      let expReg = /^\d{6}$/
      if (!expReg.test(value)) {
        callback(new Error(this.$t('scoreEntryMana.validateMessage')))
      } else {
        callback()
      }
    },
    // 获取时间
    getTime(timeStamp) {
      return INDEX.parseTime(new Date(timeStamp), '{y}/{m}/{d} {h}:{i}:{s}')
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1
      this.getListData()
    },
    // 修改学期
    changeCalendarId(val) {
      this.queryForm.condition.examType = ''
      this.getScoreEntryTime()
    },
    // 获取当前学期的成绩录入时间
    getScoreEntryTime(type) {
      // 获取当前学期的成绩录入时间
      scoreManagementApi.queryScoreEntryTime({
        "calendarId": this.queryForm.condition.calendarId,
        "examType": this.queryForm.condition.examType
      }).then(res => {
        if (res.code === 200) {
          if (res.data.length > 0) {
            this.enterabledTime.hasRight = true
            // 已设置本学年学期成绩录入开关，考试类型：期末总评/重缓考
            this.queryForm.condition.examType = res.data[0].inputType
            this.enterabledTime.startTime = this.getTime(res.data[0].startTime)
            this.enterabledTime.endTime = this.getTime(res.data[0].stopTime)
            this.admitToEntryType = res.data[0].inputTypeDetails
          } else {
            if (!type) {
              this.queryForm.condition.examType = '2'
            }
            this.enterabledTime.hasRight = false
          }
          this.onSubmit()
        }
      })
    },
    getListData() {
      scoreManagementApi.queryFinalAssessResults(this.queryForm).then((res) => {
        this.dataList = res.data.list
        this.queryForm.total_ = res.data.total_
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val
      this.getListData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val
      this.getListData()
    },
    reset() {
      this.$nextTick(() => {
        this.queryForm.condition.calendarId = ''
        this.$refs.calendarSelect.init()
      })
      this.onSubmit()
    },
    // 修改考试类型
    changeExamType(val) {
      this.queryForm.condition.examType = val
      this.getScoreEntryTime('changeExamType')
    },
    // 空白登分表
    scoreBlankSheet(row) {
      this.detailInfo = {
        "calendarId": row.calendarId,
        "examType": row.examType,
        "teachingClassId": row.teachingClassId,
        "faculty": row.faculty,
        "isBlank": "Y"
      }
      this.indexKey = 2
    },
    // 查看
    selectCourseInfo(row) {
      this.detailInfo = {
        "calendarId": row.calendarId,
        "examType": row.examType,
        "teachingClassId": row.teachingClassId,
        "faculty": row.faculty
      }
      this.indexKey = 3
    },
    // 存档成绩单
    checkToBlanket(row){
      let params=`/api/scoremanagementservice/minorScoreEntryController/archiveTranscripts?teachingClassId=${row.teachingClassId}&calendarId=${row.calendarId}&examType=${row.examType}&faculty=${row.faculty}`
      window.open(params)
    },
    // 成绩录入
    scoreEntry(row) {
      scoreManagementApi.validateGradeEntry({
        "calendarId": row.calendarId,
        "courseCode": row.courseCode,
        "faculty": row.faculty,
        "teachingClassId": row.teachingClassId,
        "examType": row.examType
      }).then(res => {
        if (res.code === 200) {
          if (this.needMessageVerification) {
            scoreManagementApi.sendMessage({
              "pushType": 0,
              "type": 1
            }).then(res => {
              if (res.code === 200) {
                this.messageInfo = res.data
                this.passwordNum = res.data.id
                this.title = this.$t('scoreEntryMana.messageValidate')
                this.dialogVisible = true
                this.detailInfo = {
                  "condition": { 
                    "calendarId": row.calendarId,
                    "courseCode": row.courseCode,
                    "courseName": row.courseName,
                    "courseNo": row.courseNo,
                    "faculty": row.faculty,
                    "teachingClassId": row.teachingClassId,
                    "examType": row.examType
                  }
                }
              }
            })
          } else {
            this.detailInfo = {
              "condition": { 
                "calendarId": row.calendarId,
                "courseCode": row.courseCode,
                "courseName": row.courseName,
                "courseNo": row.courseNo,
                "faculty": row.faculty,
                "teachingClassId": row.teachingClassId,
                "examType": row.examType
              }
            }
            this.indexKey = 4
          }
        }
      })
    },
    // 清空成绩
    deleterScore(row){
        let params={
            teachingClassId: row.teachingClassId,
            calendarId: row.calendarId,
            courseCode: row.courseCode,
            examType: this.queryForm.condition.examType
        }
        this.$delConfirm(this.$t('此操作会清空成绩构成和已录入的成绩，您确定吗？'),"提示").then(() => {
            scoreManagementApi.clearScoreEntries(params).then(({code,data})=>{
                if (code !== 200) return;
                this.$message({
                    message: '成功清空成绩构成和已录入的成绩！',
                    type: 'success'
                });
                this.getListData();
            })
        })
    },
    beforeClose() {
      this.dialogForm.verificationCode = ''
      this.$refs['dialogForm'].clearValidate()
      this.dialogVisible = false
    },
    // 取消
    cancel(dialogName) {
      this.dialogForm.verificationCode = ''
      this.$refs[dialogName].clearValidate()
      this.dialogVisible = false
    },
    // 确定
    confirm(dialogName) {
      this.$refs[dialogName].validate(valid => {
        if (valid) {
          scoreManagementApi.validateMessage({
            "id": this.messageInfo.id,
            "code": this.dialogForm.verificationCode,
            "receiverCode": this.messageInfo.receiverCode
          }).then(res => {
            if (res.code === 200) {
              this.dialogForm.verificationCode = ''
              this.$refs[dialogName].clearValidate()
              this.dialogVisible = false
              this.indexKey = 4
            }else{
              this.dialogForm.verificationCode = ''
              this.$refs[dialogName].clearValidate()
              this.dialogVisible = false
              return;
            }
          })
        }
      })
    },
    refreshMainPage() {
      this.multipleSelection = []
      this.indexKey = 1
      this.onSubmit()
    }
  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            // 空白登分表
            if (item.authCode === 'scoreEntryMana-blankScoreSheet') {
              this.permitToScoreBlankSheet = true;
            }
            // 查看
            if (item.authCode === 'scoreEntryMana-select') {
              this.permitToDetail = true;
            }
            // 成绩录入(未发布)
            if (item.authCode === 'scoreEntryMana-score-entry') {
              this.permitToScoreEntry = true;
            }
            // // 导入/下载模板
            // if (item.authCode === 'scoreEntryMana-overall-eval-sub') {
            //   this.permitToSubTotalEvalScoreSheet = true;
            // }
            // // 导出
            // if (item.authCode === 'scoreEntryMana-overall-eval-sub') {
            //   this.permitToSubTotalEvalScoreSheet = true;
            // }
          });
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
  .condition-card ::v-deep {
    .el-row {
      height: 30px!important;
    }
    .el-form-item {
      margin-bottom: 0!important;
    }
  }
  .condition-title {
    color: #2b3b4e;
    font-size: 18px;
    line-height: 24px;
    font-weight: bold;
  }

</style>